package mnnu.ghbe.controller;

import mnnu.ghbe.service.RankingService;
import mnnu.ghbe.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/rankings")
public class RankingController {
    
    @Autowired
    private RankingService rankingService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @GetMapping
    public RankingService.RankingResult getAllRankings(@RequestHeader("Authorization") String token) {
        try {
            // 从JWT token中提取用户ID
            String jwtToken = token.replace("Bearer ", "");
            if (!jwtUtil.validateToken(jwtToken)) {
                // 如果token无效，返回不包含用户排名的排行榜
                return new RankingService.RankingResult(rankingService.getTop15Rankings(), null, -1);
            }
            
            Long userId = jwtUtil.getUserIdFromToken(jwtToken);
            if (userId == null) {
                // 如果无法提取用户ID，返回不包含用户排名的排行榜
                return new RankingService.RankingResult(rankingService.getTop15Rankings(), null, -1);
            }
            
            // 返回前15名排行榜和用户自己的排名
            return rankingService.getTop15RankingsWithUserRanking(userId);
        } catch (Exception e) {
            // 出现异常时，返回不包含用户排名的排行榜
            return new RankingService.RankingResult(rankingService.getTop15Rankings(), null, -1);
        }
    }
}